<template>
  <div>
    <h2>Login</h2>
    <form @submit.prevent="login">
      <div>
        <label for="username">Username:</label>
        <input type="text" id="username" v-model="username" required>
      </div>
      <div>
        <label for="password">Password:</label>
        <input type="password" id="password" v-model="password" required>
      </div>
      <button type="submit">Login</button>
    </form>
    <p v-if="errorMessage" style="color: red;">{{ errorMessage }}</p>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      username: '',
      password: '',
      errorMessage: ''
    };
  },
  methods: {
    async login() {
      try {
        const response = await axios.post('http://localhost:8080/login', {
          username: this.username,
          password: this.password
        });

        // 根据后端返回的结果处理
        if (response.data.success) {
          // 登录成功，处理跳转逻辑或显示成功消息
          // 示例：跳转到 dashboard 页面
          this.$router.push('/dashboard');
        } else {
          // 登录失败，显示错误消息
          this.errorMessage = response.data.message;
        }
      } catch (error) {
        // 处理异常情况，显示通用错误消息
        this.errorMessage = 'Login failed. Please try again later.';
      }
    }
  }
};
</script>

<style>
/* 样式 */
</style>
